package com.lz.ccjdemo.http.subscriber;

import android.app.Activity;
import android.app.AlertDialog;
import android.util.Log;

import com.lz.ccjdemo.App;
import com.lz.ccjdemo.act.MainActivity;
import com.lz.ccjdemo.http.IHttpCall;
import com.lz.ccjdemo.http.data.BaseResultData;
import com.lz.ccjdemo.utils.IntentUtils;
import com.lz.ccjdemo.utils.dialog.SimpleDialog;

import org.json.JSONException;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import retrofit2.HttpException;


/**
 * 带BaseResultData 的订阅
 *
 * @param <T> 数据对象 既返回的数据对象
 * @name lz
 * @time 2019/8/26 16:01
 */
public abstract class SimpleBaseSubscriber<T> extends BaseSubscriber<BaseResultData<T>> implements IHttpCall<T> {

    public final String TAG = "Http ";

    private void error(Throwable e) {
        String result = getApiExceptionMsg(e);
        BaseResultData<T> resultData = new BaseResultData<>();
        resultData.setCode(-1);
        resultData.setMessage(result);
        onFail(resultData);
    }

    @Override
    public void onFail(BaseResultData<T> t) {
        Log.e(TAG, "error code=" + t.getCode() + " error message=" + t.getMessage());
    }

    @Override
    public void onNext(BaseResultData<T> t) {
        if (t == null) {
            error(new Exception("服务器错误"));
            return;
        }
        if (t.getCode() == 200) {
            onSuccess(t.getData());
            return;
        }
        if (t.getCode() == 500) {
            new SimpleDialog.Builder(App.getApp().getCurActivity()).setTitleStr("title")
                    .setCancelStr("cancel")
                    .setConfirmStr("confirm")
                    .setContextStr("context")
                    .setDialogListener(new SimpleDialog.OnDefaultDialogListener() {
                        @Override
                        public void onCancel(AlertDialog dialog) {
                            dialog.dismiss();
                        }

                        @Override
                        public void onConfirm(AlertDialog dialog) {
                            dialog.dismiss();
                        }
                    }).build();
            return;
        }
        if (t.getCode() == 800) {
            IntentUtils.builder(App.getApp().getCurActivity()).start(MainActivity.class);
            return;
        }
        onFail(t);
    }

    private String getApiExceptionMsg(Throwable e) {
        String result = "";
        if (e != null) {
            //统一处理HttpException
            if (e instanceof HttpException) {
                try {
                    switch (((HttpException) e).code()) {
                        //400 Bad Request：客户端发送的请求无效。
                        //401 Unauthorized：请求需要用户认证。
                        //403 Forbidden：服务器拒绝处理请求，通常因为权限不足。
                        //404 Not Found：请求的资源不存在。
                        case 400:
                            result = "code 400 请求无效";
                            break;
                        case 401:
                            result = "code 401 请求需要用户认证";
                            break;
                        case 403:
                            result = "code 403 拒绝处理请求,权限不足";
                            break;
                        case 404:
                            result = "code 404 您访问资源不存在，请稍后再尝试。";
                            break;
                        case 500:
                            result = "code 500 服务器开小差了，请稍后再尝试。";
                            break;
                        default:
                            result = "code " + ((HttpException) e).code() + " 网络异常，请稍后再尝试。";
                            break;
                    }
                } catch (Exception e1) {
                    result = "网络异常，请稍后再尝试。";
                }
            } else if (e instanceof TimeoutException || e instanceof SocketTimeoutException) {
                result = "网络连接超时";
            } else if (e instanceof UnknownHostException) {
                result = "网络异常";
            } else if (e instanceof JSONException) {
                result = "数据解析异常";
            } else {
                //其他异常
                result = "数据异常，请稍后再尝试。";
            }
        } else {
            result = "服务器连接失败";
        }
        e.printStackTrace();
        return result;
    }

}
